home *** CD-ROM | disk | FTP | other *** search
/ Aminet 32 / Aminet 32 (1999)(Schatztruhe)[!][Aug 1999].iso / Aminet / dev / lang / Python151_Src.lha / Python1.5_Source / Objects / floatobject.c < prev    next >
C/C++ Source or Header  |  1998-01-26  |  14KB  |  611 lines

  1. /***********************************************************
  2. Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam,
  3. The Netherlands.
  4.  
  5.                         All Rights Reserved
  6.  
  7. Permission to use, copy, modify, and distribute this software and its
  8. documentation for any purpose and without fee is hereby granted,
  9. provided that the above copyright notice appear in all copies and that
  10. both that copyright notice and this permission notice appear in
  11. supporting documentation, and that the names of Stichting Mathematisch
  12. Centrum or CWI or Corporation for National Research Initiatives or
  13. CNRI not be used in advertising or publicity pertaining to
  14. distribution of the software without specific, written prior
  15. permission.
  16.  
  17. While CWI is the initial source for this software, a modified version
  18. is made available by the Corporation for National Research Initiatives
  19. (CNRI) at the Internet address ftp://ftp.python.org.
  20.  
  21. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH
  22. REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
  23. MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH
  24. CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
  25. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
  26. PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  27. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  28. PERFORMANCE OF THIS SOFTWARE.
  29.  
  30. ******************************************************************/
  31.  
  32. /* Float object implementation */
  33.  
  34. /* XXX There should be overflow checks here, but it's hard to check
  35.    for any kind of float exception without losing portability. */
  36.  
  37. #include "Python.h"
  38.  
  39. #include <ctype.h>
  40. #include "mymath.h"
  41.  
  42. #include "protos/floatobject_protos.h"
  43.  
  44. #ifdef i860
  45. /* Cray APP has bogus definition of HUGE_VAL in <math.h> */
  46. #undef HUGE_VAL
  47. #endif
  48.  
  49. #if defined(HUGE_VAL) && !defined(CHECK)
  50. #define CHECK(x) if (errno != 0) ; \
  51.     else if (-HUGE_VAL <= (x) && (x) <= HUGE_VAL) ; \
  52.     else errno = ERANGE
  53. #endif
  54.  
  55. #ifndef CHECK
  56. #define CHECK(x) /* Don't know how to check */
  57. #endif
  58.  
  59. #ifdef HAVE_LIMITS_H
  60. #include <limits.h>
  61. #endif
  62.  
  63. #ifndef LONG_MAX
  64. #define LONG_MAX 0X7FFFFFFFL
  65. #endif
  66.  
  67. #ifndef LONG_MIN
  68. #define LONG_MIN (-LONG_MAX-1)
  69. #endif
  70.  
  71. #ifdef __NeXT__
  72. #ifdef __sparc__
  73. /*
  74.  * This works around a bug in the NS/Sparc 3.3 pre-release
  75.  * limits.h header file.
  76.  * 10-Feb-1995 bwarsaw@cnri.reston.va.us
  77.  */
  78. #undef LONG_MIN
  79. #define LONG_MIN (-LONG_MAX-1)
  80. #endif
  81. #endif
  82.  
  83. #if !defined(__STDC__) && !defined(macintosh)
  84. extern double fmod Py_PROTO((double, double));
  85. extern double pow Py_PROTO((double, double));
  86. #endif
  87.  
  88. #ifdef sun
  89. /* On SunOS4.1 only libm.a exists. Make sure that references to all
  90.    needed math functions exist in the executable, so that dynamic
  91.    loading of mathmodule does not fail. */
  92. double (*_Py_math_funcs_hack[])() = {
  93.     acos, asin, atan, atan2, ceil, cos, cosh, exp, fabs, floor,
  94.     fmod, log, log10, pow, sin, sinh, sqrt, tan, tanh
  95. };
  96. #endif
  97.  
  98. /* Special free list -- see comments for same code in intobject.c. */
  99. static PyFloatObject *free_list = NULL;
  100. #define BLOCK_SIZE    1000    /* 1K less typical malloc overhead */
  101. #define N_FLOATOBJECTS    (BLOCK_SIZE / sizeof(PyFloatObject))
  102.  
  103. static PyFloatObject *
  104. fill_free_list()
  105. {
  106.     PyFloatObject *p, *q;
  107.     p = PyMem_NEW(PyFloatObject, N_FLOATOBJECTS);
  108.     if (p == NULL)
  109.         return (PyFloatObject *)PyErr_NoMemory();
  110.     q = p + N_FLOATOBJECTS;
  111.     while (--q > p)
  112.         *(PyFloatObject **)q = q-1;
  113.     *(PyFloatObject **)q = NULL;
  114.     return p + N_FLOATOBJECTS - 1;
  115. }
  116.  
  117. PyObject *
  118. #ifdef __SC__
  119. PyFloat_FromDouble(double fval)
  120. #else
  121. PyFloat_FromDouble(fval)
  122.     double fval;
  123. #endif
  124. {
  125.     register PyFloatObject *op;
  126.     if (free_list == NULL) {
  127.         if ((free_list = fill_free_list()) == NULL)
  128.             return NULL;
  129.     }
  130.     op = free_list;
  131.     free_list = *(PyFloatObject **)free_list;
  132.     op->ob_type = &PyFloat_Type;
  133.     op->ob_fval = fval;
  134.     _Py_NewReference(op);
  135.     return (PyObject *) op;
  136. }
  137.  
  138. static void
  139. float_dealloc(op)
  140.     PyFloatObject *op;
  141. {
  142.     *(PyFloatObject **)op = free_list;
  143.     free_list = op;
  144. }
  145.  
  146. double
  147. PyFloat_AsDouble(op)
  148.     PyObject *op;
  149. {
  150.     PyNumberMethods *nb;
  151.     PyFloatObject *fo;
  152.     double val;
  153.     
  154.     if (op && PyFloat_Check(op))
  155.         return PyFloat_AS_DOUBLE((PyFloatObject*) op);
  156.     
  157.     if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
  158.         nb->nb_float == NULL) {
  159.         PyErr_BadArgument();
  160.         return -1;
  161.     }
  162.     
  163.     fo = (PyFloatObject*) (*nb->nb_float) (op);
  164.     if (fo == NULL)
  165.         return -1;
  166.     if (!PyFloat_Check(fo)) {
  167.         PyErr_SetString(PyExc_TypeError,
  168.                 "nb_float should return float object");
  169.         return -1;
  170.     }
  171.     
  172.     val = PyFloat_AS_DOUBLE(fo);
  173.     Py_DECREF(fo);
  174.     
  175.     return val;
  176. }
  177.  
  178. /* Methods */
  179.  
  180. void
  181. PyFloat_AsString(buf, v)
  182.     char *buf;
  183.     PyFloatObject *v;
  184. {
  185.     register char *cp;
  186.     /* Subroutine for float_repr and float_print.
  187.        We want float numbers to be recognizable as such,
  188.        i.e., they should contain a decimal point or an exponent.
  189.        However, %g may print the number as an integer;
  190.        in such cases, we append ".0" to the string. */
  191.     sprintf(buf, "%.12g", v->ob_fval);
  192.     cp = buf;
  193.     if (*cp == '-')
  194.         cp++;
  195.     for (; *cp != '\0'; cp++) {
  196.         /* Any non-digit means it's not an integer;
  197.            this takes care of NAN and INF as well. */
  198.         if (!isdigit(Py_CHARMASK(*cp)))
  199.             break;
  200.     }
  201.     if (*cp == '\0') {
  202.         *cp++ = '.';
  203.         *cp++ = '0';
  204.         *cp++ = '\0';
  205.     }
  206. }
  207.  
  208. /* ARGSUSED */
  209. static int
  210. float_print(v, fp, flags)
  211.     PyFloatObject *v;
  212.     FILE *fp;
  213.     int flags; /* Not used but required by interface */
  214. {
  215.     char buf[100];
  216.     PyFloat_AsString(buf, v);
  217.     fputs(buf, fp);
  218.     return 0;
  219. }
  220.  
  221. static PyObject *
  222. float_repr(v)
  223.     PyFloatObject *v;
  224. {
  225.     char buf[100];
  226.     PyFloat_AsString(buf, v);
  227.     return PyString_FromString(buf);
  228. }
  229.  
  230. static int
  231. float_compare(v, w)
  232.     PyFloatObject *v, *w;
  233. {
  234.     double i = v->ob_fval;
  235.     double j = w->ob_fval;
  236.     return (i < j) ? -1 : (i > j) ? 1 : 0;
  237. }
  238.  
  239. static long
  240. float_hash(v)
  241.     PyFloatObject *v;
  242. {
  243.     double intpart, fractpart;
  244.     int expo;
  245.     long x;
  246.     /* This is designed so that Python numbers with the same
  247.        value hash to the same value, otherwise comparisons
  248.        of mapping keys will turn out weird */
  249.  
  250. #ifdef MPW /* MPW C modf expects pointer to extended as second argument */
  251. {
  252.     extended e;
  253.     fractpart = modf(v->ob_fval, &e);
  254.     intpart = e;
  255. }
  256. #else
  257.     fractpart = modf(v->ob_fval, &intpart);
  258. #endif
  259.  
  260.     if (fractpart == 0.0) {
  261.         if (intpart > 0x7fffffffL || -intpart > 0x7fffffffL) {
  262.             /* Convert to long int and use its hash... */
  263.             PyObject *w = PyLong_FromDouble(v->ob_fval);
  264.             if (w == NULL)
  265.                 return -1;
  266.             x = PyObject_Hash(w);
  267.             Py_DECREF(w);
  268.             return x;
  269.         }
  270.         x = (long)intpart;
  271.     }
  272.     else {
  273.         /* Note -- if you change this code, also change the copy
  274.            in complexobject.c */
  275.         long hipart;
  276.         fractpart = frexp(fractpart, &expo);
  277.         fractpart = fractpart * 2147483648.0; /* 2**31 */
  278.         hipart = (long)fractpart; /* Take the top 32 bits */
  279.         fractpart = (fractpart - (double)hipart) * 2147483648.0;
  280.                         /* Get the next 32 bits */
  281.         x = hipart + (long)fractpart + (long)intpart + (expo << 15);
  282.                         /* Combine everything */
  283.     }
  284.     if (x == -1)
  285.         x = -2;
  286.     return x;
  287. }
  288.  
  289. static PyObject *
  290. float_add(v, w)
  291.     PyFloatObject *v;
  292.     PyFloatObject *w;
  293. {
  294.     double result;
  295.     PyFPE_START_PROTECT("add", return 0)
  296.     result = v->ob_fval + w->ob_fval;
  297.     PyFPE_END_PROTECT(result)
  298.     return PyFloat_FromDouble(result);
  299. }
  300.  
  301. static PyObject *
  302. float_sub(v, w)
  303.     PyFloatObject *v;
  304.     PyFloatObject *w;
  305. {
  306.     double result;
  307.     PyFPE_START_PROTECT("subtract", return 0)
  308.     result = v->ob_fval - w->ob_fval;
  309.     PyFPE_END_PROTECT(result)
  310.     return PyFloat_FromDouble(result);
  311. }
  312.  
  313. static PyObject *
  314. float_mul(v, w)
  315.     PyFloatObject *v;
  316.     PyFloatObject *w;
  317. {
  318.     double result;
  319.  
  320.     PyFPE_START_PROTECT("multiply", return 0)
  321.     result = v->ob_fval * w->ob_fval;
  322.     PyFPE_END_PROTECT(result)
  323.     return PyFloat_FromDouble(result);
  324. }
  325.  
  326. static PyObject *
  327. float_div(v, w)
  328.     PyFloatObject *v;
  329.     PyFloatObject *w;
  330. {
  331.     double result;
  332.     if (w->ob_fval == 0) {
  333.         PyErr_SetString(PyExc_ZeroDivisionError, "float division");
  334.         return NULL;
  335.     }
  336.     PyFPE_START_PROTECT("divide", return 0)
  337.     result = v->ob_fval / w->ob_fval;
  338.     PyFPE_END_PROTECT(result)
  339.     return PyFloat_FromDouble(result);
  340. }
  341.  
  342. static PyObject *
  343. float_rem(v, w)
  344.     PyFloatObject *v;
  345.     PyFloatObject *w;
  346. {
  347.     double vx, wx;
  348.     double /* div, */ mod;
  349.     wx = w->ob_fval;
  350.     if (wx == 0.0) {
  351.         PyErr_SetString(PyExc_ZeroDivisionError, "float modulo");
  352.         return NULL;
  353.     }
  354.     PyFPE_START_PROTECT("modulo", return 0)
  355.     vx = v->ob_fval;
  356.     mod = fmod(vx, wx);
  357.     /* div = (vx - mod) / wx; */
  358.     if (wx*mod < 0) {
  359.         mod += wx;
  360.         /* div -= 1.0; */
  361.     }
  362.     PyFPE_END_PROTECT(mod)
  363.     return PyFloat_FromDouble(mod);
  364. }
  365.  
  366. static PyObject *
  367. float_divmod(v, w)
  368.     PyFloatObject *v;
  369.     PyFloatObject *w;
  370. {
  371.     double vx, wx;
  372.     double div, mod;
  373.     wx = w->ob_fval;
  374.     if (wx == 0.0) {
  375.         PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
  376.         return NULL;
  377.     }
  378.     PyFPE_START_PROTECT("divmod", return 0)
  379.     vx = v->ob_fval;
  380.     mod = fmod(vx, wx);
  381.     div = (vx - mod) / wx;
  382.     if (wx*mod < 0) {
  383.         mod += wx;
  384.         div -= 1.0;
  385.     }
  386.     PyFPE_END_PROTECT(div)
  387.     return Py_BuildValue("(dd)", div, mod);
  388. }
  389.  
  390. static double powu(x, n)
  391.     double x;
  392.     long n;
  393. {
  394.     double r = 1.;
  395.     double p = x;
  396.     long mask = 1;
  397.     while (mask > 0 && n >= mask) {
  398.         if (n & mask)
  399.             r *= p;
  400.         mask <<= 1;
  401.         p *= p;
  402.     }
  403.     return r;
  404. }
  405.  
  406. static PyObject *
  407. float_pow(v, w, z)
  408.     PyFloatObject *v;
  409.     PyObject *w;
  410.     PyFloatObject *z;
  411. {
  412.     double iv, iw, ix;
  413.     long intw;
  414.  /* XXX Doesn't handle overflows if z!=None yet; it may never do so :(
  415.   * The z parameter is really only going to be useful for integers and
  416.   * long integers.  Maybe something clever with logarithms could be done.
  417.   * [AMK]
  418.   */
  419.     iv = v->ob_fval;
  420.     iw = ((PyFloatObject *)w)->ob_fval;
  421.     intw = (long)iw;
  422.     if (iw == intw && -10000 < intw && intw < 10000) {
  423.         /* Sort out special cases here instead of relying on pow() */
  424.         if (intw == 0) {         /* x**0 is 1, even 0**0 */
  425.             PyFPE_START_PROTECT("pow", return 0)
  426.              if ((PyObject *)z!=Py_None) {
  427.                  ix=fmod(1.0, z->ob_fval);
  428.                  if (ix!=0 && z->ob_fval<0) ix+=z->ob_fval;
  429.             }
  430.              else ix=1.0;
  431.             PyFPE_END_PROTECT(ix)
  432.                 return PyFloat_FromDouble(ix); 
  433.         }
  434.         errno = 0;
  435.         PyFPE_START_PROTECT("pow", return 0)
  436.         if (intw > 0)
  437.             ix = powu(iv, intw);
  438.         else
  439.             ix = 1./powu(iv, -intw);
  440.         PyFPE_END_PROTECT(ix)
  441.     }
  442.     else {
  443.         /* Sort out special cases here instead of relying on pow() */
  444.         if (iv == 0.0) {
  445.             if (iw < 0.0) {
  446.                 PyErr_SetString(PyExc_ValueError,
  447.                        "0.0 to a negative power");
  448.                 return NULL;
  449.             }
  450.             return PyFloat_FromDouble(0.0);
  451.         }
  452.         if (iv < 0.0) {
  453.             PyErr_SetString(PyExc_ValueError,
  454.                    "negative number to a float power");
  455.             return NULL;
  456.         }
  457.         errno = 0;
  458.         PyFPE_START_PROTECT("pow", return 0)
  459.         ix = pow(iv, iw);
  460.         PyFPE_END_PROTECT(ix)
  461.     }
  462.     CHECK(ix);
  463.     if (errno != 0) {
  464.         /* XXX could it be another type of error? */
  465.         PyErr_SetFromErrno(PyExc_OverflowError);
  466.         return NULL;
  467.     }
  468.      if ((PyObject *)z!=Py_None) {
  469.         PyFPE_START_PROTECT("pow", return 0)
  470.          ix=fmod(ix, z->ob_fval);    /* XXX To Be Rewritten */
  471.          if ( ix!=0 &&
  472.               ((iv<0 && z->ob_fval>0) || (iv>0 && z->ob_fval<0) )) {
  473.              ix+=z->ob_fval;
  474.             }
  475.         PyFPE_END_PROTECT(ix)
  476.     }
  477.     return PyFloat_FromDouble(ix);
  478. }
  479.  
  480. static PyObject *
  481. float_neg(v)
  482.     PyFloatObject *v;
  483. {
  484.     return PyFloat_FromDouble(-v->ob_fval);
  485. }
  486.  
  487. static PyObject *
  488. float_pos(v)
  489.     PyFloatObject *v;
  490. {
  491.     Py_INCREF(v);
  492.     return (PyObject *)v;
  493. }
  494.  
  495. static PyObject *
  496. float_abs(v)
  497.     PyFloatObject *v;
  498. {
  499.     if (v->ob_fval < 0)
  500.         return float_neg(v);
  501.     else
  502.         return float_pos(v);
  503. }
  504.  
  505. static int
  506. float_nonzero(v)
  507.     PyFloatObject *v;
  508. {
  509.     return v->ob_fval != 0.0;
  510. }
  511.  
  512. static int
  513. float_coerce(pv, pw)
  514.     PyObject **pv;
  515.     PyObject **pw;
  516. {
  517.     if (PyInt_Check(*pw)) {
  518.         long x = PyInt_AsLong(*pw);
  519.         *pw = PyFloat_FromDouble((double)x);
  520.         Py_INCREF(*pv);
  521.         return 0;
  522.     }
  523.     else if (PyLong_Check(*pw)) {
  524.         *pw = PyFloat_FromDouble(PyLong_AsDouble(*pw));
  525.         Py_INCREF(*pv);
  526.         return 0;
  527.     }
  528.     return 1; /* Can't do it */
  529. }
  530.  
  531. static PyObject *
  532. float_int(v)
  533.     PyObject *v;
  534. {
  535.     double x = PyFloat_AsDouble(v);
  536.     if (x < 0 ? (x = ceil(x)) < (double)LONG_MIN
  537.               : (x = floor(x)) > (double)LONG_MAX) {
  538.         PyErr_SetString(PyExc_OverflowError,
  539.                 "float too large to convert");
  540.         return NULL;
  541.     }
  542.     return PyInt_FromLong((long)x);
  543. }
  544.  
  545. static PyObject *
  546. float_long(v)
  547.     PyObject *v;
  548. {
  549.     double x = PyFloat_AsDouble(v);
  550.     return PyLong_FromDouble(x);
  551. }
  552.  
  553. static PyObject *
  554. float_float(v)
  555.     PyObject *v;
  556. {
  557.     Py_INCREF(v);
  558.     return v;
  559. }
  560.  
  561.  
  562. static PyNumberMethods float_as_number = {
  563.     (binaryfunc)float_add, /*nb_add*/
  564.     (binaryfunc)float_sub, /*nb_subtract*/
  565.     (binaryfunc)float_mul, /*nb_multiply*/
  566.     (binaryfunc)float_div, /*nb_divide*/
  567.     (binaryfunc)float_rem, /*nb_remainder*/
  568.     (binaryfunc)float_divmod, /*nb_divmod*/
  569.     (ternaryfunc)float_pow, /*nb_power*/
  570.     (unaryfunc)float_neg, /*nb_negative*/
  571.     (unaryfunc)float_pos, /*nb_positive*/
  572.     (unaryfunc)float_abs, /*nb_absolute*/
  573.     (inquiry)float_nonzero, /*nb_nonzero*/
  574.     0,        /*nb_invert*/
  575.     0,        /*nb_lshift*/
  576.     0,        /*nb_rshift*/
  577.     0,        /*nb_and*/
  578.     0,        /*nb_xor*/
  579.     0,        /*nb_or*/
  580.     (coercion)float_coerce, /*nb_coerce*/
  581.     (unaryfunc)float_int, /*nb_int*/
  582.     (unaryfunc)float_long, /*nb_long*/
  583.     (unaryfunc)float_float, /*nb_float*/
  584.     0,        /*nb_oct*/
  585.     0,        /*nb_hex*/
  586. };
  587.  
  588. PyTypeObject PyFloat_Type = {
  589.     PyObject_HEAD_INIT(&PyType_Type)
  590.     0,
  591.     "float",
  592.     sizeof(PyFloatObject),
  593.     0,
  594.     (destructor)float_dealloc, /*tp_dealloc*/
  595.     (printfunc)float_print, /*tp_print*/
  596.     0,            /*tp_getattr*/
  597.     0,            /*tp_setattr*/
  598.     (cmpfunc)float_compare, /*tp_compare*/
  599.     (reprfunc)float_repr, /*tp_repr*/
  600.     &float_as_number,    /*tp_as_number*/
  601.     0,            /*tp_as_sequence*/
  602.     0,            /*tp_as_mapping*/
  603.     (hashfunc)float_hash, /*tp_hash*/
  604. };
  605.  
  606. void
  607. PyFloat_Fini()
  608. {
  609.     /* XXX Alas, the free list is not easily and safely freeable */
  610. }
  611.